package com.himiotech.core.framework.config.shiro.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.himiotech.core.framework.config.async.AsyncFactory;
import com.himiotech.core.framework.config.async.AsyncManager;
import com.himiotech.core.framework.helper.constant.ShiroConstants;
import com.himiotech.core.framework.helper.constant.UserConstants;
import com.himiotech.core.framework.helper.utils.ServletUtils;
import com.himiotech.core.project.data.mapper.RoleMapper;
import com.himiotech.core.project.data.mapper.UserRoleMapper;
import com.himiotech.core.project.model.entity.role.Role;
import com.himiotech.core.project.model.entity.user.User;
import com.himiotech.core.project.model.entity.user.UserRole;
import com.himiotech.core.project.model.metadata.RoleMetadata;
import com.himiotech.core.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;

/**
 * 注册校验方法
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Service
public class RegisterService {

    @Autowired
    private IUserService userService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 注册
     */
    @Transactional(rollbackFor = Exception.class)
    public String register(User user) {
        String msg = "", loginName = user.getLoginName(), password = user.getPassword();

        if (ObjectUtil.isNotEmpty(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) {
            msg = "验证码错误";
        } else if (StrUtil.isEmpty(loginName)) {
            msg = "用户名不能为空";
        } else if (StrUtil.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (loginName.length() < UserConstants.USERNAME_MIN_LENGTH
                || loginName.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(loginName))) {
            msg = "保存用户'" + loginName + "'失败，注册账号已存在";
        } else {
            user.setPwdUpdateDate(new Date());
            user.setUserName(loginName);
            boolean regFlag = userService.registerUser(user);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                Role commonRole = roleMapper.selectOne(Wrappers.<Role>query().eq(RoleMetadata.ROLE_KEY.getColName(), "common"));
                if (commonRole == null) {
                    Role role = new Role();
                    role.setRoleName("普通角色");
                    role.setRoleKey("common");
                    role.setRoleSort("2");
                    role.setDataScope("2");
                    role.setStatus("0");
                    role.setDelFlag("0");
                    roleMapper.insert(role);
                    userRoleMapper.batchUserRole(Collections.singletonList(UserRole.builder().roleId(role.getRoleId()).userId(user.getUserId()).build()));
                } else {
                    userRoleMapper.batchUserRole(Collections.singletonList(UserRole.builder().roleId(commonRole.getRoleId()).userId(user.getUserId()).build()));
                }
                AsyncManager.me().execute(AsyncFactory.recordLoginInfo(loginName, "Register", "注册成功"));
            }
        }
        return msg;
    }
}
